<template>
  <div>
    <!-- -----------------------------------------------------基本信息-------------------------------------------------------------- -->
    <el-divider>基本信息</el-divider>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" inline class="rule_form">

      <div class="dialog_left">

        <el-form-item label="采购标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入采购标题" />
        </el-form-item>

        <el-form-item label="采购类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择采购类型" @change="handleOptions">
            <el-option label=" 设备采购" value="0">
            </el-option>
            <el-option label="物料采购" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="期望供货日期" prop="desiredDeliveryTime">
          <el-date-picker type="date" placeholder="请选择供货日期" :picker-options="pickerOptions"
            v-model="ruleForm.desiredDeliveryTime" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>

        <el-form-item label="购置理由" prop="reason">
          <el-input v-model="ruleForm.reason" placeholder="请输入购置理由" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注信息" />
        </el-form-item>
      </div>
      <!-- -----------------------------------------------------添加采购品【按钮】及弹框-------------------------------------------------------------- -->
      <div class="dialog_btn">
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAddPurchase">添加采购品</el-button>
      </div>
      <Purchase ref="purchase_form" @click_create_submit="handleSlectList" />
      <!-- ---------------------------------------------------物料采购表格----------------------------------------------------------- -->
      <div class="dialog_table">
        <el-table :data="ruleForm.SubmitSelectList" max-height="550px" style="width: 100%" v-if="ruleForm.type == 1">
          <el-table-column label="序号" width="100">
            <template slot-scope="scope">
              <div> {{ scope.$index + 1 }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="materialNum" label="物料编号" width="160" />
          <el-table-column prop="materialName" label="物料名称" />
          <el-table-column prop="typeName" label="物料类别" />
          <el-table-column prop="model" label="物料规格型号" show-overflow-tooltip>
            <template slot-scope="{row}">
              <div> {{ row.model || '-' }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="supplierName" label="物料供应商" show-overflow-tooltip />
          <el-table-column prop="unitName" label="物料单位" />
          <el-table-column prop="amount" label="物料类型">
            <template slot-scope="{row}">
              <dict-tags :options="SparePartsAndConsumables" :value="row.kind" />
            </template>
          </el-table-column>
          <!-- <el-table-column prop="avgPrice" label="物料参考单价（元）" /> -->
          <el-table-column label="采购单价（元）">
            <template slot-scope="scope">
              <el-form-item :prop="'SubmitSelectList.' + scope.$index + '.price'" :rules="rules.fileType">
                <el-input-number style="width:100%;margin-top: 20px;" :min="0" :controls="false"
                  v-model="scope.row.price" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="采购数量">
            <template slot-scope="scope">
              <el-form-item :prop="'SubmitSelectList.' + scope.$index + '.overplusAmount'" :rules="rules.fileNum">
                <el-input-number style="width:100%;margin-top: 20px;" :min="1" :controls="false"
                  @input.native="onInput0_100" v-model="scope.row.overplusAmount" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="物料总库存">
            <template slot-scope="{row}">
              <div> {{ row.amount || '0' }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="操作" width="220" fixed="right">
            <template slot-scope="scope">
              <el-button size="small" icon="el-icon-delete" type="danger" @click="handledelete(scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- ---------------------------------------------------设备采购表格----------------------------------------------------------- -->
      <div class="dialog_table">
        <el-table :data="ruleForm.SubmitSelectList" style="width: 100%" max-height="550px" v-if="ruleForm.type == 0">
          <el-table-column label="序号" width="100">
            <template slot-scope="scope">
              <div> {{ scope.$index + 1 }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="equipmentName" label="设备名称" width="160" />
          <el-table-column prop="brand" label="设备品牌" width="160" />
          <el-table-column prop="typeName" label="设备类别" width="160" />
          <el-table-column prop="model" label="设备规格型号" width="160" />
          <el-table-column prop="supplierName" label="设备供应商" width="160" show-overflow-tooltip />
          <el-table-column prop="unitName" label="设备单位" width="160" />
          <el-table-column label="采购单价（元）" width="160">
            <template slot-scope="scope">
              <el-form-item :prop="'SubmitSelectList.' + scope.$index + '.price'" :rules="rules.fileType">
                <el-input-number style="width:100%;margin-top: 20px;" :min="0" :controls="false"
                  v-model="scope.row.price" />
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column label="设备状态" width="160">
            <template slot-scope="{row}">
              <dict-tag :options="statusFlag" :value="row.status" />
            </template>
          </el-table-column> -->
          <el-table-column label="是/否计量设备" width="160">
            <template slot-scope="{row}">
              <div>{{ ['是', '否'][row.meterageFlag] }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="meterageNum" label="计量编号" width="160">
            <template slot-scope="{row}">
              <div> {{ row.meterageNum || '-' }} </div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="操作" fixed="right" width="220">
            <template slot-scope="scope">
              <el-button size="small" icon="el-icon-delete" type="danger" @click="handledelete(scope.$index)">删除
              </el-button>
              <el-button size="small" type="primary" icon="el-icon-view" @click="handleSelectImage(scope.row.image)">图片
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- ---------------------------------------------------审核信息----------------------------------------------------------- -->
      <el-divider>审核信息</el-divider>
      <div class="rule_form_audit">
        <el-form-item label="审核人" prop="auditVosUser">
          <el-select v-model="ruleForm.auditVosUser" collapse-tags multiple placeholder="请选择审核人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="" style="margin-left:120px">
          <span v-for="(tag, index) in tagUserList" :key="index">
            <el-tag closable disable-transitions @close="tagChange(tag, index)">
              <span>{{ tag.name }}</span>
            </el-tag>
            <span style="font-size:28px;position: relative;top: 5px;">
              <template v-if="index !== tagUserList.length - 1">
                <i class="el-icon-caret-right"></i>
              </template>
            </span>
          </span>

        </el-form-item>
        <el-form-item label="抄送人">
          <el-select v-model="ruleForm.auditVosType" multiple placeholder="请选择抄送人" style="width:100%">
            <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
    </el-form>
    <template v-if="ImageOpen">
      <Dialog-image :src="imageSrc" />
    </template>
    <!-- ---------------------------------------------------提交及取消【按钮】----------------------------------------------------------- -->
    <div class="form_btn">
      <el-button type="primary" @click="handleSubmitForm">提交</el-button>
      <el-button @click="handleCloseForm">取消</el-button>
    </div>
  </div>
</template>

<script>
import { add, getuserlist, listDetail } from '@/api/purchasing/purchasing'
// import Purchase from './purchase.vue'
/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  title: "", //采购标题
  type: "0", //采购类型（0设备采购 1物料采购）
  desiredDeliveryTime: "", //预期供货时间
  reason: "", //购置理由
  remark: "", //备注
  SubmitSelectList: [],// 列表提交总数据展示
  auditVosUser: [],// 审核人
  auditVosType: []// 抄送人
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */

export default {
  name: 'detailedform',
  components: {
    Purchase
  },
  data () {
    return {
      ruleForm,
      formFLag: false,
      imageSrc: undefined,//图片预览参数
      ImageOpen: false,
      allUserData: [],//用户信息列表
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7; //只能选择今天及今天之后的日期
          //return time.getTime() < Date.now() - 8.64e6; //只能选择今天之后的日期，今天的日期也不能选
        }
      },
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        title: [
          { required: true, message: '请输入采购标题', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择采购类型', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        desiredDeliveryTime: [
          { required: true, message: '请选择供货日期', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        reason: [
          { required: true, message: '请输入购置理由', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        fileType: [
          { required: true, message: '请输入采购单价', trigger: 'blur' }
        ],
        fileNum: [
          { required: true, message: '请输入采购数量', trigger: 'blur' }
        ],
        auditVosUser: { required: true, message: '请选择审核人', trigger: 'change' },
        auditVosType: { required: true, message: '请选择抄送人', trigger: 'change' },
      }
    }
  },
  computed: {
    // 审核人数据转换--------------------------
    tagUserList () {
      let Arr = []
      this.ruleForm.auditVosUser.map(item => {
        this.allUserData.map(value => {
          if (item === value.userId) {
            Arr.push({
              userId: value.userId,
              name: value.userName
            })
          }
        })
      })
      return Arr
    },
  },
  created () {
    this.getlist()
  },
  methods: {
    // 重新申请的回显事件--------------
    handlegetFormlist (id) {
      if (id) {
        this.formFLag = true
        listDetail(id).then(({ data: res }) => {
          console.log(res);
          this.ruleForm.title = res.title;
          this.ruleForm.type = res.type;
          this.ruleForm.desiredDeliveryTime = res.desiredDeliveryTime;
          this.ruleForm.reason = res.reason;
          this.ruleForm.remark = res.remark;
          if (res.type == 1) {
            this.ruleForm.SubmitSelectList = res.purchaseConsumableVos.map(item => item.consPriceAndAmountVo) || []
          } else {
            this.ruleForm.SubmitSelectList = res.purchaseEquipmentVos.map(item => {
              return {
                ...item.purchaseEquipmentBaseVo,
                price: item.price
              }
            }) || []
          }
        })
      } else {
        this.formFLag = false
      }
    },
    // ----------添加采购品【按钮】 ------------------
    handleAddPurchase () {
      this.$refs['purchase_form'].openDialog(this.ruleForm.type)
    },
    async getlist () {
      // 用户列表接口-------------------------
      const userdata = await getuserlist();
      this.allUserData = userdata.data
    },
    // 表单采购类型选择器切换
    handleOptions () {
      this.ruleForm.SubmitSelectList = []
    },
    // 接收子组件勾选后的数据
    handleSlectList (val) {
      console.log(val);
      const arr = [...this.ruleForm.SubmitSelectList, ...val];
      this.ruleForm.SubmitSelectList = this.removedup(arr, this.ruleForm.type == 0 ? 'equipmentBaseId' : 'consumableBaseId');
    },
    fn2 (arr) {
      const res = new Map();
      return arr.filter(arr => !res.has(arr.consumableBaseId) && res.set(arr.consumableBaseId, arr.consumableBaseId));
    },
    //列表的删除事件
    handledelete (index) {
      this.ruleForm.SubmitSelectList.splice(index, 1)
    },
    // 审核人删除事件
    tagChange (val, index) {
      this.ruleForm.auditVosUser.splice(index, 1)
    },
    onInput0_100 (e) {
      this.$message.closeAll();
      // 验证是否是纯数字
      let isNumber = /^\d*$/.test(e.target.value);
      // 过滤非数字
      e.target.value = e.target.value.replace(/\D/g, "");
      if (!isNumber || e.target.value < 0) {
        this.$message.warning("只能输入整数");
      }
      e.target.value = (e.target.value >= 0 && e.target.value.match(/^\d*/g)[0]) || null;
    },
    // 表单总提交事件
    handleSubmitForm () {
      // console.log('Form总提交数据',this.ruleForm);
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // -------------------------------------------------------重组表格列表提交数据--------------------------------------------
          let equipmentList = []
          let data = {}
          if (this.ruleForm.type == 0) {
            // 设备提交列表数据重组
            equipmentList = this.ruleForm.SubmitSelectList.map(item => {
              return {
                equipmentBaseId: item.equipmentBaseId,//设备基质ID
                price: item.price,//采购单价
              }
            })
            data.purchaseEquipmentVos = equipmentList
          } else if (this.ruleForm.type == 1) {
            // 物料提交列表数据重组
            equipmentList = this.ruleForm.SubmitSelectList.map(item => {
              return {
                consumableBaseId: item.consumableBaseId,//备件物料 ID
                price: item.price,// 采购单价
                amount: item.overplusAmount,// 总库存数量
                // overplusAmount: item.overplusAmount// 采购数量
              }
            })
            data.purchaseConsumableVos = equipmentList
          }
          // -------------------------------------------------审核人和抄送人数据重组------------------------------------------
          const examine = this.ruleForm.auditVosUser.map(item => {
            return {
              userId: item,
              userType: 0
            }
          })//审核人
          const copy = this.ruleForm.auditVosType.map(item => {
            return {
              userId: item,
              userType: 1
            }
          })// 抄送人
          // ----------------------------------------------------总数据拼接----------------------------------------------------
          data.title = this.ruleForm.title
          data.type = this.ruleForm.type
          data.desiredDeliveryTime = this.ruleForm.desiredDeliveryTime
          data.reason = this.ruleForm.reason
          data.remark = this.ruleForm.remark
          data.auditVos = examine.concat(copy)
          add(data).then(() => {
            this.$emit('form_submit_click')
            this.$message.success(this.formFLag ? '重新申请采购成功！' : '新增采购申请成功！');
            this.handleRemove();
          })
        } else {
          this.$message.error('提交表单验证信息不通过，请重新输入');
        }
      })
    },
    handleRemove () {
      for (const k in this.ruleForm) {
        this.ruleForm[k] = ''
      }
      this.ruleForm.type = '0'
      this.ruleForm.SubmitSelectList = []
      this.ruleForm.auditVosUser = []
      this.ruleForm.auditVosType = []
    },
    // 表单取消事件
    handleCloseForm () {
      this.handleRemove()
      this.$emit('form_submit_click')
    },
    // 查看图片
    handleSelectImage (src) {
      this.imageSrc = src
      this.ImageOpen = true
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog_table {
  margin-top: 20px;
}

.rule_form {
  .el-select {
    width: 300px;
  }

  .el-input {
    width: 300px;
  }
}

/* el-descriptions-item 文字居中 */
::v-deep .el-descriptions__body .el-descriptions__table .el-descriptions-item__cell {
  text-align: center;
}

.rule_form_audit {
  width: 26%;
  margin: auto;
}

.dialog_btn {
  margin: 10px 45px;
}



.form_btn {
  width: 42%;
  display: flex;
  justify-content: center;
  margin: 50px auto 20px auto;
}
</style>